<?php


namespace com\verify;
use lunzi\TpSms;

class Sms  extends  TpSms
{

    // 验证码过发送间隔的时间
    protected $interval = 60;
    protected $intervalName = 'interval';
    protected $mobile = '';




    /**
     * 获取间隔key
     * @return str
     */
    protected function getIntervalKey()
    {
        $this->mobile = input($this->mobileName);
        $cacheKey = $this->cachePrefix.$this->scene.$this->intervalName.$this->mobile;
        return $cacheKey;
    }

    /**
     * 验证码间隔校验
     * @return bool
     */
    public function checkInterval()
    {
       if(cache($this->getIntervalKey())){
           return true;
       }
       return false;
    }


    /**
     * 发送短信验证码
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author Mr.Li longfei
     * @create 2021-05-22 10:18
     */
    public function sendSms(){

        $sendObj = new DxjSms();
        $params['code'] = $this->code;
        //不管何种场景都用2发送
        $sendRes = $sendObj->sendSms(2,$this->mobile,$params);
        if($sendRes['status'] != 1){
            $this->error = $sendRes['msg'];
            return false;
        }
        return true;
    }

    /**
     * 生成验证码
     * @return string
     * @throws \Exception
     */
    public function create()
    {
        if(!$this->checkInterval()){
            $this->expire = config('sms.code_expire'); //设置验证码有效期
            parent::create();
            $this->sendSms();
            $cacheKey = $this->getIntervalKey();
            //        增加ip验证
            $cacheVal = $this->code.ip2long(request()->ip());
            cache($cacheKey,$cacheVal,$this->interval);
        }else{
            $this->error = '不能频繁发送';
        }
        return $this;

    }

    /**
     * @return string
     * @author Mr.Li longfei
     * @create 2021-05-22 10:24
     */
    public function getCode()
    {
        return $this->code;

    }




}
